package com.ryan.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ryan.security.core.properties.LoginType;
import com.ryan.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by kaimin on 1/1/2019.
 * time : 22:20
 * 登录成之后会被调用,写过之后，需要在应用中告知容器，要用自定义的，不要用默认的
 */
@Component("simpleAuthenticationSuccessHandler")
@Slf4j
//public class SimpleAuthenticationSuccessHandler implements AuthenticationSuccessHandler{
public class SimpleAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{
    //第二种是 换成由用户自己定义返回的是json还是转发url

    //登录成之后会被调用

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    /**
     *
     * @param request
     * @param response
     * @param authentication 封装的认证信息 session，用户信息等
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        log.info("登录成功");
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));

        } else {
            //父类的方法就是跳转
            super.onAuthenticationSuccess(request,response,authentication);
        }

//        response.setContentType("application/json;charset=UTF-8");
//        response.getWriter().write(objectMapper.writeValueAsString(authentication));
    }
}
